<?php

namespace app\backstage\controller;

use think\Controller;
use think\Request;
use think\captcha\Captcha;
use app\backstage\model\Admin;
use app\backstage\model\Role;
use app\backstage\model\Auth;
use app\backstage\model\HouseBroker;
use think\Validate;
use Db;

class Index extends Controller
{


      /**
     * 显示资源列表
     *
     * @return \think\Response
     */
    public function index(Request $request)
    {

      $role_id = $request->role_id;  //在登录中间件传入的角色id

      $auth_ids = Role::where('id',$role_id)->value('auth_ids');

      if(!$auth_ids){
        return redirect(config('template.root_path').'/login');
      }  

      //权限菜单
      $authList = Auth::where('id','in',$auth_ids)->where('is_menu',1)->order(['sort desc','id asc'])->select();

      $parentMenu = array();
      $sonMenu = array();
      if($authList){
          foreach($authList as $k => $v){
              if($v['pid']==0){
                  $parentMenu[$v['id']] = $v;
              }
          }   

          foreach($authList as $sv){
                if($sv['pid']>0){
                    $sonMenu[$sv['pid']][] = $sv;
                }
          }
      }


      //我的经纪人
       $brokers = HouseBroker::where('admin_id',$request->admin_id)->select();


      return  view('index',['parentMenu'=>$parentMenu,'sonMenu'=>$sonMenu,'brokers'=>$brokers]);
    }


    
    /**
     * 登录
     *
     * @return \think\Response
     */
    public function login(Request $request)
    {
        if($request->isAjax()){

            $data = $request->post();
            
            //验证必传参数
            $validate = new Validate([
                'username'  => 'require',
                'password'  => 'require',
                'captcha|验证码'=>'require|captcha'
            ]);

            if (!$validate->check($data)) {
                return ['code'=>101,'msg'=>$validate->getError()];
            }

            $admin  = new Admin();

            //查询管理员信息
            $pwd  = md5( md5($data['password']).config('database.password_salt') );
            $res = $admin->where('name|phone|email',$data['username'])->where('password',$pwd)->where('status',1)->find();



            if($res){

                $login_token = md5($res['phone'].time());
                
                //更新登录信息
                $loginData = array(
                  'login_ip' =>$_SERVER["REMOTE_ADDR"],
                  'login_time' =>time(),
                  'login_token' => $login_token
                );

                $upd = $admin->save($loginData,['id'=>$res['id']]);

                if(!$upd) return ['code'=>102,'系统繁忙'];

                if(!empty($data['seven_status'])){
                    //7天免登陆
                    cookie('login_token',$login_token,86400*7);
                }else{
                    cookie('login_token',$login_token);
                }

                return ['code'=>200];
            }else{

                return ['code'=>101,'msg'=>'账号或密码错误'];
            }


        }

        return  view('login');
    }

    //验证码
    public function verify(){
        ob_clean();
        $captcha = new Captcha(config('captcha.'));
        return $captcha->entry();
    }

  

     /**
     * 显示欢迎页
     *
     * @return \think\Response
     */
    public function welcome(Request $request)
    {

      return  view('welcome');
    }


    public function test(){




//        die;
       $data = Db::name('new_house')->field('id,lng,lat')->limit(100)->select();


       dump($data);die;
     foreach($data as $k=>$v){
         $x = sprintf("%.5f",(mt_rand() / mt_getrandmax()));
         $y = sprintf("%.6f",(mt_rand() / mt_getrandmax()));

         echo Db::name('new_house')->where('id',$v['id'])->update(['lng'=>114+$x,'lat'=>23+$y]);
     }
    }

    /**
     * 显示图标页.
     *
     * @return \think\Response
     */
    public function unicode()
    {
        return view('unicode');
    }


    /**
     * 客服
     */
    public function service($broker_id){


        $broker = HouseBroker::where('id',$broker_id)->find();


        return view('chat/index',['broker'=>$broker,'imgPath'=>config('api.oss_img_path'),'hx_appkey'=>config('api.hx_appkey')]);
    }



    //输入音频
    public function readAudio(Request $request){
        header("Content-type:audio/mp3");

        $url = $request->param('audioUrl');

        $res = curl_get($url);
        echo 'data:audio/x-mpeg;base64,'.base64_encode($res);

    }


}
